package com.wenkang.stu.util;

import com.alibaba.fastjson.JSONArray;
import com.wenkang.stu.pojo.Account;
import com.wenkang.stu.pojo.SysUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Date;
import java.util.List;

public class JwtUtils {
    // 过期时间（单位：毫秒）
    private static final int EXPIRATION = 1000 * 60 * 60 * 24 * 7;

    // 密钥
    private static final String APP_SECRET_KEY = "KangKang123";

    private static final String AUTHORITIES_CLAIM = "authorities";
    private static final String USERNAME_CLAIM = "username";


    public static String generateToken(UserDetails user) {
        return Jwts.builder()
                .claim(USERNAME_CLAIM, user.getUsername())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION))
                .signWith(SignatureAlgorithm.HS512, APP_SECRET_KEY)
                .compact();
    }

    /**
     * 生成jwt token
     */
    public static String generateToken(SysUser user) {
        return Jwts.builder()
                .claim(USERNAME_CLAIM, user.getUsername())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION))
                .signWith(SignatureAlgorithm.HS512, APP_SECRET_KEY)
                .compact();
    }

    public static String generateToken(Account account) {
        return Jwts.builder()
                .claim(USERNAME_CLAIM, account.getUsername())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION))
                .signWith(SignatureAlgorithm.HS512, APP_SECRET_KEY)
                .compact();
    }

    /**
     * 检查token 并返回token中存储的数据
     *
     * @param token
     * @return
     */
    public static Claims checkJWT(String token) {
        try {
            return Jwts.parser()
                    .setSigningKey(APP_SECRET_KEY)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private static Claims getClaims(String token) {
        return Jwts.parser().setSigningKey(APP_SECRET_KEY).parseClaimsJws(token).getBody();
    }

    /**
     * 是否过期
     *
     * @param token
     * @return
     */
    public static boolean isExpiration(String token) {
        Claims claims = getClaims(token);
        return claims.getExpiration().before(new Date());
    }

    /**
     * 获取用户名
     *
     * @param token
     * @return
     */
    public static String getUsername(String token) {
        Claims claims = getClaims(token);
        return claims.get(USERNAME_CLAIM).toString();
    }

    public static List<SimpleGrantedAuthority> getAuthorities(String token) {
        Claims claims = getClaims(token);
        List authorities = (List) claims.get(AUTHORITIES_CLAIM);
        String authoritiesStr = JSONArray.toJSONString(authorities);
        return JSONArray.parseArray(authoritiesStr, SimpleGrantedAuthority.class);
    }


}